/*
 * @Author: Marte
 * @Date:   2016-10-25 15:50:45
 * @Last Modified by:   Marte
 * @Last Modified time: 2016-11-04 15:01:40
 */

'use strict';

var oracledb = require('../utils/oracleUtil');
var _ = require('underscore');
var Promise = require('bluebird');

var controller = {

};

/**
 * [getJsonByTypeRemark 根据指定证件类型和评语获取图片]
 * @param  {[type]}   req  [description]
 * @param  {[type]}   res  [description]
 * @param  {Function} next [description]
 * @return {[type]}        [Json]
 */
controller.getJsonByTypeRemark = function(req, res, next) {
    var typeId = req.query.typeid;
    var remarkId = req.query.remarkid;
    /*    var getPics = PicTypeRemarkGroup.findJsonByTypeAndRemark(typeId, remarkId);*/

    var conn;
    oracledb.connection()
        .then(function(connection) {
            conn = connection;
            return conn.execute('SELECT pictyperemarkgroup.*,remarkgroup.groupName,' +
                'remark.remark,type.typeName,pic.fileName,' +
                'pic.fileFullName,pic.origName From pictyperemarkgroup ' +
                ' Left Join remarkgroup On remarkgroup.id=pictyperemarkgroup.RemarkGroupId ' +
                ' Left Join remark On remark.id=pictyperemarkgroup.RemarkId ' +
                ' Left Join type On type.id=pictyperemarkgroup.TypeId ' +
                ' Left Join pic On pic.id=pictyperemarkgroup.PicId Where ' +
                ' pictyperemarkgroups.TypeId=:typeId ' +
                ' and pictyperemarkgroups.RemarkId=:remarkId', {
                    typeId: typeId,
                    remarkId: remarkId
                });
        })
        .then(function(pics) {
            conn.close();
            return res.status(200).json(pics.rows);
        })
        .catch(function(err) {
            conn.close();
            return res.status(500).json({
                error: '读取数据出错！',
                syserror: err.message
            });
        });
};

/**
 * [getJsonByTypeRemark 根据指定证件类型和评语获取图片并按评语组分组]
 * @param  {[type]}   req  [description]
 * @param  {[type]}   res  [description]
 * @param  {Function} next [description]
 * @return {[type]}        [Json]
 */
controller.getAndGroupByGroupNameByTypeRemark = function(req, res, next) {
    var typeId = req.query.typeid;
    var remarkId = req.query.remarkid;

    var conn;
    oracledb.connection()
        .then(function(connection) {
            conn = connection;
            return conn.execute('SELECT pictyperemarkgroup.*,remarkgroup.groupName,' +
                'remark.remark,type.typeName,pic.fileName,' +
                'pic.fileFullName,pic.origName From pictyperemarkgroup ' +
                ' Left Join remarkgroup On remarkgroup.id=pictyperemarkgroup.RemarkGroupId ' +
                ' Left Join remark On remark.id=pictyperemarkgroup.RemarkId ' +
                ' Left Join type On type.id=pictyperemarkgroup.TypeId ' +
                ' Left Join pic On pic.id=pictyperemarkgroup.PicId Where ' +
                ' pictyperemarkgroup.TypeId=:typeId ' +
                ' and pictyperemarkgroup.RemarkId=:remarkId', {
                    typeId: typeId,
                    remarkId: remarkId
                });
        })
        .then(function(pics) {
            conn.close();
            //获取到数据后，将数据按RemarkGroupId分组
            var picsByGroup = {};
            _.each(pics.rows, function(item, i) {
                if (!picsByGroup[item.GROUPNAME]) {
                    picsByGroup[item.GROUPNAME] = [
                        item
                    ];
                } else {
                    picsByGroup[item.GROUPNAME].push(item);
                }
            });

            //console.log(picsByGroup);
            return res.status(200).json(picsByGroup);
        })
        .catch(function(err) {
            conn.close();
            return res.status(500).json({
                error: '读取数据出错！',
                syserror: err.message
            });
        });
};

/**
 * [postInputDataToJson 提交相片类型评语分组并保存到服务器]
 * @param  {[type]}   req  [description]
 * @param  {[type]}   res  [description]
 * @param  {Function} next [description]
 * @return {[type]}        [description]
 */
controller.postInputDataToJson = function(req, res, next) {
    var inputObj = req.body.input;
    //console.log(inputObj);

    if (inputObj.remark && inputObj.typeName && inputObj.picGroup.length > 0) {
        var setTypeRemark = [];
        var setBefore = [];

        var hasValidGroup = false;
        //先判断是否存在有效分组
        _.each(inputObj.picGroup, function(picGroup, i) {
            if (picGroup.pic.length > 1) {
                hasValidGroup = true;
                return;
            }
        });

        if (hasValidGroup) {

            var conn;
            oracledb.connection()
                .then(function(connection) {
                    conn = connection;
                    //不存在证件类型则新增，返回证件类型ID
                    return conn.execute('Select id From type Where typeName=:typeName', {
                            typeName: inputObj.typeName
                        })
                        .then(function(_result) {
                            if (_result.rows.length > 0) {
                                return _result.rows[0].ID;
                            } else {
                                return conn.execute('Insert Into type(id,typeName) Values(type_seq.nextval,:typeName) RETURNING id INTO :ID', {
                                    typeName: inputObj.typeName,
                                    ID: { type: oracledb.NUMBER, dir: oracledb.BIND_OUT }
                                }).then(function(result) {
                                    return result.outBinds.ID[0];
                                });
                            }
                        })
                })
                .then(function(_typeId) {
                    inputObj.typeId = _typeId;
                    //不存在评语则新增，返回评语ID
                    return conn.execute('select id From remark Where remark=:remark', {
                            remark: inputObj.remark
                        })
                        .then(function(_result) {
                            if (_result.rows.length > 0) {
                                return _result.rows[0].ID;
                            } else {
                                return conn.execute('Insert Into remark(id,remark) values(remark_seq.nextval,:remark) RETURNING id INTO :ID', {
                                    remark: inputObj.remark,
                                    ID: { type: oracledb.NUMBER, dir: oracledb.BIND_OUT }
                                }).then(function(result) {
                                    return result.outBinds.ID[0];
                                });
                            }
                        });

                })
                .then(function(_remarkId) {
                    inputObj.remarkId = _remarkId;
                    var setBefore = [];
                    //证件类型和评语关系表不存在则保存
                    setBefore.push(conn.execute('Select 1 From typeRemark Where typeId=:typeId and remarkId=:remarkId', {
                            typeId: inputObj.typeId,
                            remarkId: inputObj.remarkId
                        })
                        .then(function(_result) {
                            if (_result.rows.length <= 0) {
                                conn.execute('insert Into typeRemark(id,typeId,remarkId) values(typeRemark_seq.nextval,:typeId,:remarkId)', {
                                    typeId: inputObj.typeId,
                                    remarkId: inputObj.remarkId
                                });
                            }
                        }));
                    _.each(inputObj.picGroup, function(picGroup, i) {
                        //该分组的图片项是否大于1
                        if (picGroup.pic.length > 1) {
                            //分组+评语不存在则保存,并更新分组ID
                            setBefore.push(conn.execute('Select id From remarkGroup ' + ' Where remarkId=:remarkId and groupName=:groupName', {
                                    remarkId: inputObj.remarkId,
                                    groupName: picGroup.groupName
                                })
                                .then(function(_result) {
                                    if (_result.rows.length > 0) {
                                        return _result.rows[0].ID;
                                    } else {
                                        return conn.execute(' Insert Into remarkGroup(id,remarkId,groupName)' +
                                                ' values(remarkGroup_seq.nextval,' +
                                                ':remarkId,:groupName)  RETURNING id INTO :ID', {
                                                    remarkId: inputObj.remarkId,
                                                    groupName: picGroup.groupName,
                                                    ID: {
                                                        type: oracledb.NUMBER,
                                                        dir: oracledb.BIND_OUT
                                                    }
                                                })
                                            .then(function(result) {
                                                return result.outBinds.ID[0];
                                            });
                                    }
                                })
                                .then(function(_groupId) {
                                    picGroup.id = _groupId;
                                }));
                        }
                    });
                    return Promise.all(setBefore);
                })
                .then(function() {
                    var setInput = [];
                    _.each(inputObj.picGroup, function(picGroup) {
                        //该分组的图片项是否大于1
                        if (picGroup.pic.length > 1) {
                            _.each(picGroup.pic, function(pic) {
                                if (pic.id) {
                                    //图片名称有改变则更新
                                    setInput.push(conn.execute('Update pic set fileName=:fileName Where id=:id ' +
                                        'and fileName<>:fileName', {
                                            id: pic.id,
                                            fileName: pic.fileName
                                        }));
                                    //不存在则增加图片证件类型评语分组关系记录
                                    setInput.push(conn.execute('select 1 From picTypeRemarkGroup Where ' +
                                            'picId=:picId and typeId=:typeId and remarkId=:remarkId and remarkGroupId=:remarkGroupId', {
                                                remarkId: inputObj.remarkId,
                                                typeId: inputObj.typeId,
                                                remarkGroupId: picGroup.id,
                                                picId: pic.id
                                            })
                                        .then(function(_result) {
                                            if (_result.rows.length <= 0) {
                                                conn.execute('Insert Into picTypeRemarkGroup(id,picId,typeId,remarkId,remarkGroupId) ' +
                                                    'Values(picTypeRemarkGroup_seq.nextval,:picId,:typeId,:remarkId,:remarkGroupId)', {
                                                        remarkId: inputObj.remarkId,
                                                        typeId: inputObj.typeId,
                                                        remarkGroupId: picGroup.id,
                                                        picId: pic.id
                                                    });
                                            }
                                        }));
                                }
                            });
                        }
                    });
                    return Promise.all(setInput);
                })
                .then(function() {
                    conn.close();
                    res.status(200).json({ success: 'ok' });
                })
                .catch(function(err) {
                    conn.close();
                    return res.status(500).json({
                        error: '保存失败.',
                        syserror: err.message
                    });
                });

        } else {
            return res.status(400).json({
                error: '没有有效的分组相片信息.',
                syserror: '没有有效的分组相片信息.'
            });
        }

    }

};

controller.registerPath = function(router) {

    /*根据证件类型和评语获取图片并按评语组别分组*/
    router.addPathGetHanlder('/api/picTypeRemarkGroups/groupbygroupname', controller.getAndGroupByGroupNameByTypeRemark);

    /*根据证件类型和评语获取图片*/
    router.addPathGetHanlder('/api/picTypeRemarkGroups', controller.getJsonByTypeRemark);

    /*保存证件类型、评语、图片分组*/
    router.addPathPostHanlder('/pictyperemarkgroups', controller.postInputDataToJson);
};

module.exports = controller;
